package com.chs.service.impl;

import com.chs.model.Product;
import com.chs.model.ProductHistory;
import com.chs.model.SystemInfo;
import com.chs.dao.ProductMapper;
import com.chs.exception.ServiceException;
import com.chs.service.ProductHistoryService;
import com.chs.service.ProductService;
import com.chs.service.SystemInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.chs.util.FileUtil;
import com.chs.util.SourceUtil;
import com.chs.util.TXTUtil;
import com.chs.util.TokenUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * (Product)表服务实现类
 *
 * @author mopeiwen
 * @since 2020-06-10 10:48:38
 */
@Service
@Transactional
public class ProductServiceImpl implements ProductService {
	@Resource
	private ProductMapper productMapper;
	@Resource
	private ProductHistoryService productHistoryService;
	@Resource
	private SystemInfoService systemInfoService;
	@Autowired
	private HttpServletRequest request;

	/**
	 * 通过商品ID查询单条商品数据
	 *
	 * @param pid 主键
	 * @return 实例对象
	 */
	@Override
	public Product queryById(String pid) {
		System.out.println(pid);
		return this.productMapper.selectByPrimaryKey(pid);
	}

	@Override
	public Product queryByIdForHistory(String pid) {
		// 添加浏览记录
		ProductHistory productHistory = new ProductHistory(null,
				TokenUtil.getUserId(this.request.getHeader("Authorization")), pid, DateUtil.now());
		productHistoryService.insert(productHistory);

		// 访问量++
		SystemInfo systemInfo = systemInfoService.getSystemInfo();
		systemInfo.setVisits(systemInfo.getVisits()+1);
		systemInfoService.updateSystemInfo(systemInfo);
		
		//获得商品详情
		Product product = this.productMapper.selectByPrimaryKey(pid);
		product.setPicture(TXTUtil.splitAndSplice(product.getPicture(), ",", SourceUtil.getPictureUrl()));
		System.out.println(product.getPicture());
	
		return product;
	}

	/**
	 * 通过Product对象查询集合
	 *
	 * @param product 实例对象
	 * @return 实例对象
	 */
	@Override
	public PageInfo<Product> selectAll(int pageNum, int pageSize) {
		// pageNum代表页码值，pageSize代表每页条数
		PageHelper.startPage(pageNum, pageSize);
		// 使用PageInfo来封装查询的数据
		PageInfo<Product> pageInfo = new PageInfo<Product>(productMapper.selectAll());

		//防止指针指向相同的对象
        Product product = new Product(); 
		for (int i = 0; i < pageInfo.getList().size(); i++) {
			product = pageInfo.getList().get(i);
			if (product.getPicture().contains("http")) {
				continue;
			}
			
			pageInfo.getList().get(i).setPicture(TXTUtil.splitAndSplice(pageInfo.getList().get(i).getPicture(), ",", SourceUtil.getPictureUrl()));
			System.out.println(pageInfo.getList().get(i).getPicture());
		}
		
		return pageInfo;
	}

	@Override
	public PageInfo<Product> selectAll(int pageNum, int pageSize, String uid) {
		// pageNum代表页码值，pageSize代表每页条数
		PageHelper.startPage(pageNum, pageSize);

		Product product = new Product();
		product.setUid(uid);

		// 使用PageInfo来封装查询的数据
		PageInfo<Product> pageInfo = new PageInfo<Product>(productMapper.selectAll(product));

		//防止指针指向相同的对象
		for (int i = 0; i < pageInfo.getList().size(); i++) {
			product = pageInfo.getList().get(i);
			if (product.getPicture().contains("http")) {
				continue;
			}
			
			pageInfo.getList().get(i).setPicture(TXTUtil.splitAndSplice(pageInfo.getList().get(i).getPicture(), ",", SourceUtil.getPictureUrl()));
			System.out.println(pageInfo.getList().get(i).getPicture());
		}
		
		return pageInfo;
	}

	@Override
	public PageInfo<Product> selectAllByType(int pageNum, int pageSize, String ptid) {
		// pageNum代表页码值，pageSize代表每页条数
		PageHelper.startPage(pageNum, pageSize);

		Product product = new Product();
		// ProductType productType = new ProductType(ptid);
		product.setPtid(ptid);

		// 使用PageInfo来封装查询的数据
		PageInfo<Product> pageInfo = new PageInfo<Product>(productMapper.selectAll(product));

		//防止指针指向相同的对象
		for (int i = 0; i < pageInfo.getList().size(); i++) {
			product = pageInfo.getList().get(i);
			if (product.getPicture().contains("http")) {
				continue;
			}
			
			pageInfo.getList().get(i).setPicture(TXTUtil.splitAndSplice(pageInfo.getList().get(i).getPicture(), ",", SourceUtil.getPictureUrl()));
			System.out.println(pageInfo.getList().get(i).getPicture());
		}
		
		return pageInfo;
	}

	@Override
	public PageInfo<Product> selectAllForUser(int pageNum, int pageSize) {
		// pageNum代表页码值，pageSize代表每页条数
		PageHelper.startPage(pageNum, pageSize);
		// 使用PageInfo来封装查询的数据
		PageInfo<Product> pageInfo = new PageInfo<Product>(productMapper.selectAllForUser());

		//防止指针指向相同的对象
        Product product = new Product(); 
		for (int i = 0; i < pageInfo.getList().size(); i++) {
			product = pageInfo.getList().get(i);
			if (product.getPicture().contains("http")) {
				continue;
			}
			
			pageInfo.getList().get(i).setPicture(TXTUtil.splitAndSplice(pageInfo.getList().get(i).getPicture(), ",", SourceUtil.getPictureUrl()));
			System.out.println(pageInfo.getList().get(i).getPicture());
		}
		
		return pageInfo;
	}

	/**
	 * 新增商品数据
	 *
	 * @param product 实例对象
	 * @return 实例对象
	 */
	@Override
	public boolean insert(Product product) {
		product.setReleasetime(DateUtil.now());

		product.setPutonflag(true);
		product.setExamineflag(0);
		product.setDelflag(false);

		return this.productMapper.insertSelective(product)>0;
	}

	@Override
	public boolean insertForUid(Product product) {
		product.setUid(TokenUtil.getUserId((String) request.getHeader("Authorization")));

		product.setReleasetime(DateUtil.now());

		product.setPutonflag(true);
		product.setExamineflag(0);
		product.setDelflag(false);

		return this.productMapper.insertSelective(product)>0;
	}

	// 单存图片
	@Override
	public String insertFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
		String asName = null;
		try {
			asName = "picture_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
		} catch (Exception e) {
			e.printStackTrace();
			asName = "picture_" + IdUtil.simpleUUID();
		}

		File file0 = FileUtil.upFilebySpring(file, request, response, asName, "source/picture");
		return "picture/" + file0.getName();
	}

	@Override
	public boolean insert(MultipartFile[] file, Product product, HttpServletRequest request,
			HttpServletResponse response) {
		ArrayList<String> fileVal = new ArrayList<>();
		for (int i = 0; i < file.length; i++) {
			String asName = null;
			try {
				asName = "picture" + i + "_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
			} catch (Exception e) {
				e.printStackTrace();
				asName = "picture" + i + IdUtil.simpleUUID();
			}

			File file0 = FileUtil.upFilebySpring(file[i], request, response, asName, "source/picture");
			fileVal.add("picture/" + file0.getName());
		}

		System.out.println(TXTUtil.jointStringList(fileVal, ","));
		product.setPicture(TXTUtil.jointStringList(fileVal, ","));

		if (product.getUid() == null || product.getUid().equals("")) {
			product.setUid(TokenUtil.getUserId((String) request.getHeader("Authorization")));
		}

		product.setReleasetime(DateUtil.now());

		System.out.println(product.toString());

		// 设置默认状态
		product.setPutonflag(true);
		product.setExamineflag(0);
		product.setDelflag(false);
		
		return this.productMapper.insertSelective(product)>0;
	}

	/**
	 * 管理员修改数据
	 *
	 * @param product 实例对象
	 * @return 实例对象
	 */
	@Override
	public boolean update(Product product) {

		if (product.getUid() == null || product.getUid().equals("")) {
			product.setUid(TokenUtil.getUserId((String) request.getHeader("Authorization")));
		}
		if (product.getName() == null) {
			throw new ServiceException(-1, "商品名称不能为空");
		}

		// 变回为审核状态
		product.setExamineflag(0);
		
		return this.productMapper.updateByPrimaryKeySelective(product)>0;
	}

	@Override
	public boolean updateProFile(@RequestPart MultipartFile[] file, @RequestPart Product product,
			HttpServletRequest request, HttpServletResponse response) {
		ArrayList<String> fileVal = new ArrayList<>();
		for (int i = 0; i < file.length; i++) {
			String asName = null;
			try {
				asName = "picture" + i + "_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
			} catch (Exception e) {
				e.printStackTrace();
				asName = "picture" + i + IdUtil.simpleUUID();
			}

			File file0 = FileUtil.upFilebySpring(file[i], request, response, asName, "source/picture");
			fileVal.add("picture/" + file0.getName());
		}

		System.out.println(TXTUtil.jointStringList(fileVal, ","));
		product.setPicture(TXTUtil.jointStringList(fileVal, ","));

		// 变回为审核状态
		product.setExamineflag(0);
		
		return this.productMapper.updateByPrimaryKeySelective(product)>0;
	}

	/**
	 * 通过主键（商品id）删除数据
	 *
	 * @param pid 主键
	 * @return 是否成功
	 */
	@Override
	public boolean deleteById(String pid) {
		return this.productMapper.deleteByPrimaryKey(pid) > 0;
	}

	/**
	 * 管理员批量删除商品
	 */
	@Override
	public boolean batchdeleteProduct(String pid) {
		ArrayList<String> pidList = new ArrayList<String>();
		String[] strs = pid.split(",");
		for (String str : strs) {
			pidList.add(str);
		}
		return productMapper.batchdeleteProduct(pidList)>0;
	}

	/**
	 * 管理员审核商品
	 */
	@Override
	public boolean examineProduct(Product product) {
		return this.productMapper.updateByPrimaryKeySelective(product)>0;
	}

}